package com.zzk.lanouhn.myapplication1.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.zzk.lanouhn.myapplication1.R;
import com.zzk.lanouhn.myapplication1.adapters.AllViewsAdapter;
import com.zzk.lanouhn.myapplication1.adapters.CollectArticlesDetailsAdapter;
import com.zzk.lanouhn.myapplication1.modles.AllComments;
import com.zzk.lanouhn.myapplication1.modles.AllViewsList;
import com.zzk.lanouhn.myapplication1.modles.CollectArticlesDetails;
import com.zzk.lanouhn.myapplication1.utils.HttpUtils;
import com.zzk.lanouhn.myapplication1.view.CancelCollectDialog;
import com.zzk.lanouhn.myapplication1.view.CollectDialog;
import com.zzk.lanouhn.myapplication1.view.ScrollRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * 作者信息->收藏->文章详情页面
 * Created by lanouhn on 16/9/18.
 */
public class CollectArticlesDetailsActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_title, tv_name, tv_counts, tv_comments, tv_time, tv_desc;
    private ImageView iv_icon, iv_pic, iv_back,iv_collect,iv_collected,iv_share;
    private String id;
    private CollectArticlesDetails details;//文章实体类
    private AllViewsList allViewsList;//大家都在看实体类
    private AllComments commentsList;//评论实体类
    private LinearLayout ll_comments;
    private AllViewsAdapter allViewsAdapter;
    private ScrollRecyclerView recyclerView_allviews;
    private RecyclerView contentRecy;
    private CollectDialog collectDialog;
    private CancelCollectDialog cancelCollectDialog;
    private CollectArticlesDetailsAdapter adapter;
    private List<CollectArticlesDetails.DataBean.ProductListBean> articlesContents = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collectarticlesdetails);
        initView();
        initData();
        initEvent();
        getDataFromWeb();
    }

    private void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title_list_details_collect);
        iv_icon = (ImageView) findViewById(R.id.iv_icon_author_list_collect);
        tv_name = (TextView) findViewById(R.id.tv_name_authors_list_collect);
        tv_counts = (TextView) findViewById(R.id.tv_viewcounts_list_details_collect);
        tv_comments = (TextView) findViewById(R.id.tv_comments_list_details_collect);
        tv_time = (TextView) findViewById(R.id.tv_time_list_details_collect);
        tv_desc = (TextView) findViewById(R.id.tv_desc_articles_collect);
        recyclerView_allviews = (ScrollRecyclerView) findViewById(R.id.recycler_allviews_details_list_collect);
        ll_comments = (LinearLayout) findViewById(R.id.ll_comments_details_list_collect);
        iv_back = (ImageView) findViewById(R.id.iv_back_articlelist_details_collect);
        contentRecy = (RecyclerView) findViewById(R.id.recy_articles_content_collect);
        iv_collect= (ImageView) findViewById(R.id.iv_collect_author);
        iv_collected= (ImageView) findViewById(R.id.iv_collected_author);
        iv_share= (ImageView) findViewById(R.id.iv_share_articlelist_details_collect);
    }

    private void initData() {
        Bundle bundle = this.getIntent().getExtras();
        id = bundle.getString("收藏文章内容");
    }

    private void initEvent() {
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        iv_icon.setOnClickListener(this);
        tv_name.setOnClickListener(this);
        iv_collect.setOnClickListener(this);
        iv_collected.setOnClickListener(this);
        iv_share.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_icon_author_list_collect:
            case R.id.tv_name_authors_list_collect:
                Intent intent = new Intent(CollectArticlesDetailsActivity.this, AuthorsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("authorId", details.getData().getUser().getUser_id());
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.iv_collect_author:
                iv_collected.setVisibility(View.VISIBLE);
                iv_collect.setVisibility(View.INVISIBLE);
                collectDialog=new CollectDialog(CollectArticlesDetailsActivity.this);
                Window window1=collectDialog.getWindow();
                window1.setWindowAnimations(R.style.dialogWindowAnim);
                WindowManager.LayoutParams lp1 = window1.getAttributes();
                window1.setGravity(Gravity.CENTER);
                lp1.alpha=1;
                lp1.width=320;
                lp1.height=420;
                window1.setAttributes(lp1);
                collectDialog.show();
                final Timer t1 = new Timer();
                t1.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        collectDialog.dismiss();
                        t1.cancel();
                    }
                },1500);
                break;
            case R.id.iv_collected_author:
                iv_collect.setVisibility(View.VISIBLE);
                iv_collected.setVisibility(View.INVISIBLE);
                cancelCollectDialog=new CancelCollectDialog(CollectArticlesDetailsActivity.this);
                Window window2=cancelCollectDialog.getWindow();
                window2.setWindowAnimations(R.style.dialogWindowAnim);
                WindowManager.LayoutParams lp2 = window2.getAttributes();
                window2.setGravity(Gravity.CENTER);
                lp2.alpha=1;
                lp2.width=300;
                lp2.height=400;
                window2.setAttributes(lp2);
                cancelCollectDialog.show();
                final Timer t2 = new Timer();
                t2.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        cancelCollectDialog.dismiss();
                        t2.cancel();
                    }
                },1500);
                break;
            case R.id.iv_share_articlelist_details_collect:
                showShare();
                break;
            default:

                break;
        }
    }

    private void getDataFromWeb() {
        String url = "http://open4.bantangapp.com/topic/newInfo?";
        String dataUrl = "app_id=com.jzyd.BanTang&client_id=bt_app_android" +
                "&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d" +
                "&track_user_id=2573914" +
                "&oauth_token=12977829338e5f953e3d24bcef502b6a" +
                "&track_deviceid=866479023806507" +
                "&track_device_info=x600&channel_name=leshi" +
                "&app_installtime=1471853508&app_versions=5.8.6&os_versions=5.0.2" +
                "&screensize=1080&v=18" +
                "&id=" + id +
                "&trace_id=&relate_pid=&statistics_uv=1&is_night=0";
        try {
            HttpUtils.doPostAsyn(url, dataUrl, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    details = gson.fromJson(result, CollectArticlesDetails.class);
                    articlesContents = gson.fromJson(result, CollectArticlesDetails.class).getData().getProduct_list();
                    if (details.getData().getProduct_list().size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                    if (articlesContents.size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                    String allviewsUrl = "http://open4.bantangapp.com/topics/topic/relationRec?";
                    String allviewsdataUrl = "app_id=com.jzyd.BanTang" +
                            "&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d" +
                            "&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a" +
                            "&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi" +
                            "&app_installtime=1471853508&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18" +
                            "&id=" + id;
                    try {
                        HttpUtils.doPostAsyn(allviewsUrl, allviewsdataUrl, new HttpUtils.CallBack() {
                            @Override
                            public void onRequestComplete(String result) {
                                Gson gson2 = new Gson();
                                allViewsList = gson2.fromJson(result, AllViewsList.class);
                                if (allViewsList.getData().getTopic().size() > 0) {
                                    handler.sendEmptyMessage(2);
                                } else {
                                    handler.sendEmptyMessage(0);
                                }
                                String commentsUrl = "http://open4.bantangapp.com/topics/comment/list?";
                                String commentsDataUrl = "app_id=com.jzyd.BanTang" +
                                        "&client_id=bt_app_android" +
                                        "&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d" +
                                        "&track_user_id=2573914" +
                                        "&oauth_token=12977829338e5f953e3d24bcef502b6a" +
                                        "&track_deviceid=866479023806507" +
                                        "&track_device_info=x600&channel_name=leshi" +
                                        "&app_installtime=1471853508&app_versions=5.8.6" +
                                        "&os_versions=5.0.2&screensize=1080&v=18" +
                                        "&page=0&pagesize=20&id=" + id;
                                try {
                                    HttpUtils.doPostAsyn(commentsUrl, commentsDataUrl, new HttpUtils.CallBack() {
                                        @Override
                                        public void onRequestComplete(String result) {
                                            Gson gson3 = new Gson();
                                            commentsList = gson3.fromJson(result, AllComments.class);
                                            if (commentsList.getData().size() > 0) {
                                                handler.sendEmptyMessage(3);
                                            } else {
                                                handler.sendEmptyMessage(0);
                                            }
                                        }
                                    });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:

                    break;
                case 1:
                    tv_title.setText(details.getData().getTitle());
                    tv_desc.setText(details.getData().getDesc());
                    tv_comments.setText(details.getData().getComments() + "评论");
                    tv_counts.setText(details.getData().getViews());
                    tv_time.setText("创建于 " + details.getData().getDatestr());
                    tv_name.setText(details.getData().getUser().getNickname());
                    Picasso.with(CollectArticlesDetailsActivity.this).load(details.getData().getUser().getAvatar()).into(iv_icon);
                    adapter = new CollectArticlesDetailsAdapter(CollectArticlesDetailsActivity.this, articlesContents);
                    contentRecy.setAdapter(adapter);
                    LinearLayoutManager manager=new LinearLayoutManager(CollectArticlesDetailsActivity.this);
                    manager.setOrientation(LinearLayoutManager.VERTICAL);
                    contentRecy.setLayoutManager(manager);
                    break;
                case 2:
                    allViewsAdapter = new AllViewsAdapter(CollectArticlesDetailsActivity.this, allViewsList);
                    recyclerView_allviews.setAdapter(allViewsAdapter);
                    LinearLayoutManager mnger = new LinearLayoutManager(CollectArticlesDetailsActivity.this);
                    mnger.setOrientation(LinearLayoutManager.VERTICAL);
                    recyclerView_allviews.setLayoutManager(mnger);
                    break;
                case 3:
                    String authorname = details.getData().getUser().getNickname();
                    if (commentsList.getData() != null) {

                        for (int i = 0; i < commentsList.getData().size(); i++) {
                            View view = LayoutInflater.from(CollectArticlesDetailsActivity.this).inflate(R.layout.item_comments_details, null);
                            ImageView iv_icon_users = (ImageView) view.findViewById(R.id.iv_icon_comments);
                            TextView tv_content_comments = (TextView) view.findViewById(R.id.tv_contents_comments);
                            TextView tv_name_users = (TextView) view.findViewById(R.id.tv_name_users);
                            TextView tv_time = (TextView) view.findViewById(R.id.tv_time_comments);
                            TextView tv_isAuthor = (TextView) view.findViewById(R.id.tv_isauthor);
                            Picasso.with(CollectArticlesDetailsActivity.this).load(commentsList.getData().get(i).getUser().getAvatar()).into(iv_icon_users);

                            tv_name_users.setText(commentsList.getData().get(i).getUser().getNickname());
                            tv_time.setText(commentsList.getData().get(i).getDatestr());

                            if (null != (commentsList.getData().get(i).getAt_user().getNickname())) {
                                String content = "回复 @" + commentsList.getData().get(i).getAt_user().getNickname() + ":" + commentsList.getData().get(i).getConent();
                                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content);
                                spannableStringBuilder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.mycolor)), 2, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                tv_content_comments.setText(spannableStringBuilder);
                            } else {
                                tv_content_comments.setText(commentsList.getData().get(i).getConent());
                            }

                            String commentsname = commentsList.getData().get(i).getUser().getNickname();
                            if (authorname.equals(commentsname)) {
                                tv_isAuthor.setVisibility(View.VISIBLE);
                            } else {
                                tv_isAuthor.setVisibility(View.INVISIBLE);
                            }
                            ll_comments.addView(view);
                        }
                    }
                    break;
                default:

                    break;
            }
        }
    };
    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("标题");
        // titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(this);
    }
}
